<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdmAction;
use App\Models\AdmRoleAction;
use App\Models\AdmRoleController;
use App\Models\Admrolesubmodule;
use App\User;
use \DB;
use Auth;
use Illuminate\Support\Facades\Request;

class RoleController extends CommonController
{

    /**
     * 角色列表。
     *
     * @return Response
     */
    public function getIndex()
    {
        $user_role = session('user_role');
//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        if ($user_role->type == 'System') {
            $roles = DB::table('adm_role')->orderBy('sort', 'asc')->paginate(10);
        } else {
            $roles = DB::table('adm_role')->where("pid", $user_role->id)->orderBy('sort', 'asc')->paginate(10);
        }

        return view('role.index')->with("roles", $roles)->with("actions", $this->actions);
    }

    /**
     * 角色添加页面
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getCreate()
    {
        $user_role = session('user_role');

//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        return view('role/create')->with("role", $user_role);
    }

    /**
     * 添加角色
     *
     * @return string
     */
    public function postInsert()
    {
        if (!Request::has('name')) {
            return AjaxCallbackMessage('角色名称不能为空', false);
        }
        if (!Request::has('type') || !Request::has('status') || !Request::has('pid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $name = Request::input("name");
        $type = Request::input("type");
        $status = Request::input("status");
        $pid = Request::input("pid");
        $role_id = DB::table('adm_role')->insertGetId(['name' => $name, 'type' => $type, 'status' => $status, 'pid' => $pid]);
        if ($role_id) {
            return AjaxCallbackMessage('角色添加成功', true, url('role/index'));
        } else {
            return AjaxCallbackMessage('角色添加失败', false);
        }
    }

    /**
     * 权限分配页面
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
    public function getSet()
    {
        $user_role = session('user_role');
//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        if ($user_role->type == 'System') {
            $roles = DB::table('adm_role')->orderBy('sort', 'asc')->paginate(10);
        } else {
            $roles = DB::table('adm_role')->where("pid", $user_role->id)->orderBy('sort', 'asc')->paginate(10);
        }

        return view('role.set')->with("roles", $roles);
    }

    /**
     * 分配导航页面，获取用户拥有的导航信息
     */
    public function getNav()
    {
        $rid = Request::input('rid');
        $user_role = session('user_role');
//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        $user_submodules = DB::table('adm_role_submodule')->where('role_id', $rid)->get();
        $user_submodules_arr = array();
            foreach ($user_submodules as $key => $val) {
                $user_submodules_arr[] = $val->submodule_id;
            }


        if ($user_role->type == 'System') {
            $submodules = DB::table('adm_submodule')->where('status', 1)->orderBy('sort', 'asc')->get();
        } else {
            $submodules = DB::table('adm_role_submodule as ars')
                ->join('adm_submodule as as', 'ars.submodule_id', '=', 'as.id')
                ->select('as.*')
                ->where('ars.role_id', $user_role->id)->where('as.status', 1)
                ->orderBy('as.sort', 'asc')
                ->get();
        }
        $data = array();
        foreach ($submodules as $submodule) {
            $data[$submodule->id]['id'] = $submodule->id;
            $data[$submodule->id]['name'] = $submodule->name;
            $data[$submodule->id]['code'] = $submodule->code;
            $data[$submodule->id]['parent_id'] = $submodule->pid;
            $data[$submodule->id]['got'] = in_array($submodule->id, $user_submodules_arr) ? 'checked="checked"' : '';
        }
        $data = toTree($data, 'id');

        return view('role.submodule')->with("submodules", $data)->with("role_id", $rid);
    }

    /**
     * 分配栏目页面，获取角色拥有的栏目信息
     */
    public function getMenu()
    {
        $rid = Request::input('rid');
        $user_role = session('user_role');
//        dd($user_role);
//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        $user_controllers = DB::table('adm_role_controller')->where('role_id', $rid)->get();

        //获取该角色拥有的控制器权限
        $user_controllers_arr = array();
        if (!empty($user_controllers)) {
            foreach ($user_controllers as $key => $val) {
                $user_controllers_arr[] = $val->controller_id;
            }
        }

        $user_actions = DB::table('adm_role_action')->where('role_id', $rid)->get();
        //获取该角色拥有的action权限
        $user_actions_arr = array();
        if (!empty($user_actions)) {
            foreach ($user_actions as $k => $v) {
                $user_actions_arr[] = $v->action_id;
            }
        }

        //获取该角色拥有的控制器权限
        if ($user_role->type == 'System') {
            $controllers = DB::table('adm_controller')->where('status', 1)->orderBy('id', 'asc')->get();
        } else {
            $controllers = DB::table('adm_role_controller as arc')
                ->join('adm_controller as ac', 'arc.controller_id', '=', 'ac.id')
                ->select('ac.*')
                ->where('arc.role_id', $user_role->id)->where('ac.status', 1)
                ->orderBy('ac.sort', 'asc')
                ->get();
        }


        $data = array();
        $data_actions = array();
        $actions = DB::table('adm_action')->where('status', 1)->orderBy('sort', 'asc')->get();
        foreach ($actions as $action) {
            $data_actions[$action->controller_id][] = array(
                'id'   => $action->id,
                'name' => $action->name,
                'code' => $action->code,
                'got'  => in_array($action->id, $user_actions_arr) ? 'checked="checked"' : ''
            );
        }
        foreach ($controllers as $controller) {
            $data[$controller->id]['id'] = $controller->id;
            $data[$controller->id]['submodule_id'] = $controller->submodule_id;
            $data[$controller->id]['name'] = $controller->name;
            $data[$controller->id]['code'] = $controller->code;
            $data[$controller->id]['parent_id'] = $controller->pid;
            $data[$controller->id]['got'] = in_array($controller->id, $user_controllers_arr) ? 'checked="checked"' : '';
            $data[$controller->id]['actions'] = !empty($data_actions[$controller->id]) ? $data_actions[$controller->id] : array();
        }
        $data = toTree($data, 'id');

        //获取该角色的submodule权限
        $submodules = Admrolesubmodule::with('module')->where('role_id', $rid)->get()->toArray();
        $submodules = array_column($submodules, 'submodule_id');
        return view('role.controller')->with("controllers", $data)->with("role_id", $rid)->with('submodules', $submodules);
    }

    /**
     * 为角色分配导航
     */
    public function postNav()
    {
        if (Request::has('sid') && Request::has('role_id')) {
            $role_id = Request::input('role_id');
            DB::table('adm_role_submodule')->where('role_id', $role_id)->delete();
            $sids = Request::input('sid');
            foreach ($sids as $key => $val) {
                DB::table('adm_role_submodule')->insert(['role_id' => $role_id, 'submodule_id' => $val]);
            }
        }

        return redirect(action('RoleController@getNav', ['rid' => $role_id]));
    }

    /**
     * 为角色分配栏目
     */
    public function postMenu()
    {
        $role_id = Request::input('role_id');
        $aids = Request::input('aid');
        $cids = Request::input('cid');
        if(!is_array($aids)){
            $aids = array();
        }

        if(!is_array($cids)){
            $cids = array();
        }

        AdmRoleAction::where('role_id', $role_id)->delete();
        $controllers = array();
        foreach ($aids as $k => $v) {
            AdmRoleAction::create(['role_id' => $role_id, 'action_id' => $v]);
            $action = AdmAction::where('id', $v)->first();
            $controllers[] = $action->controller_id;
        }
        $controllers = array_flip(array_flip($controllers));
        AdmRoleController::where('role_id', $role_id)->delete();
        foreach($controllers as $k=>$v){
            AdmRoleController::firstOrCreate(['role_id' => $role_id, 'controller_id' => $v]);
        }

        foreach($cids as $k=>$v){
            AdmRoleController::firstOrCreate(['role_id' => $role_id, 'controller_id' => $v]);
        }

//        if (Request::has('cid') && Request::has('role_id')) {
//            DB::table('adm_role_controller')->where('role_id', $role_id)->delete();
//            $cids = Request::input('cid');
//            foreach ($cids as $key => $val) {
//                DB::table('adm_role_controller')->insert(['role_id' => $role_id, 'controller_id' => $val]);
//            }
//            if (Request::has('aid')) {
//                DB::table('adm_role_action')->where('role_id', $role_id)->delete();
//                $aids = Request::input('aid');
//                foreach ($aids as $k => $v) {
//                    DB::table('adm_role_action')->insert(['role_id' => $role_id, 'action_id' => $v]);
//                }
//            }
//        }.
        return $this->tip('分配成功', action('RoleController@getMenu', ['rid' => $role_id]), true);
    }

    /**
     * 编辑角色
     */
    public function getEdit()
    {
        $rid = Request::input("rid");
        $role = DB::table('adm_role')->where('id', $rid)->first();
        $user_role = session('user_role');

//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        return view('role.edit')->with("role", $role)->with("user_role", $user_role);
    }

    /**
     * 更新角色信息
     *
     * @return string
     */
    public function postUpdate()
    {
        if (!Request::has('name')) {
            return AjaxCallbackMessage('角色名称不能为空', false);
        }
        if (!Request::has('id') || !Request::has('type') || !Request::has('status') || !Request::has('pid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $id = Request::input("id");
        $name = Request::input("name");
        $type = Request::input("type");
        $status = Request::input("status");
        $pid = Request::input("pid");
        DB::table('adm_role')->where('id', $id)->update(['name' => $name, 'type' => $type, 'status' => $status, 'pid' => $pid]);

        return AjaxCallbackMessage('角色编辑成功', true, url('role/index'));
    }

    /**
     * 删除角色
     *
     * @return string
     */
    public function postDelete()
    {
        if (!Request::has('rid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $rid = Request::input("rid");
        DB::table('adm_role')->where('id', '=', $rid)->delete();
        DB::table('adm_role_user')->where('role_id', '=', $rid)->delete();
        DB::table('adm_role_submodule')->where('role_id', '=', $rid)->delete();
        DB::table('adm_role_controller')->where('role_id', '=', $rid)->delete();
        DB::table('adm_role_action')->where('role_id', '=', $rid)->delete();

        return AjaxCallbackMessage('角色删除成功', true, url('role/index'));
    }

    /**
     * 用户列表
     *
     * @return Ambigous <\Illuminate\View\$this, \Illuminate\View\\Illuminate\View\View>
     */
//     public function getUser(){
//     	$users = DB::table('admin')->orderBy('sort','asc')->paginate(10);
//     	return view('role.user')->with("users",$users);
//     }

    /**
     * 分配角色页面
     */
    public function getAssign()
    {
        $uid = Request::input('uid');
        $user_role = session('user_role');
//     	$user_role = DB::table('adm_role_user as aru')->join("adm_role as ar","aru.role_id","=","ar.id")->join('admin', 'aru.admin_id', '=', 'admin.id')->select("ar.*")->where('aru.admin_id',Auth::user()->id)->first();
        if ($user_role->type == 'System') {
            $roles = DB::table('adm_role')->orderBy('sort', 'asc')->get();
        } else {
            $roles = DB::table('adm_role')->where("pid", $user_role->id)->orderBy('sort', 'asc')->get();
        }
        $select_user_role = DB::table('adm_role_user')->where('admin_id', $uid)->first();
        $select_user_role_id = !empty($select_user_role->role_id) ? $select_user_role->role_id : 0;
        echo $select_user_role_id;
        foreach ($roles as $key => $role) {
            $roles[$key]->got = $select_user_role_id == $role->id ? 'checked="checked"' : '';
        }

        return view('role.assign')->with("roles", $roles)->with("uid", $uid);
    }

    /**
     * 给后台用户分配角色
     *
     * @return string
     */
    public function postAssign()
    {
        if (!Request::has('rid')) {
            return AjaxCallbackMessage('请选择需要分配的角色', false);
        }
        if (!Request::has('uid')) {
            return AjaxCallbackMessage('数据异常', false);
        }
        $rid = Request::input("rid");
        if (count($rid) > 1) {
            return AjaxCallbackMessage('只能选择一个角色', false);
        }
        $rid = $rid[0];
        $uid = Request::input("uid");
        DB::table('adm_role_user')->where('admin_id', '=', $uid)->delete();
        DB::table('adm_role_user')->insert(['admin_id' => $uid, 'role_id' => $rid]);

        return AjaxCallbackMessage('角色分配成功', true, action('RoleController@getUser'));
    }
}